#include "tcpserver.h"
#include "ui_tcpserver.h"
#include<QHostInfo>
TCPserver::TCPserver(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TCPserver)
{
    ui->setupUi(this);
    ui->spinPort->setRange(1, 65535);  // 设置范围为 1-65535
    QString portStr = "55555";
    ui->spinPort->setValue(portStr.toInt());  // 先转为整数再设置

    QString localIP = getLocalIP();
    //QString localIP = "192.168.10.100";
    ui->comboIP->addItem(localIP);
    tcpServer = new QTcpServer(this);
    connect(tcpServer,&QTcpServer::newConnection,this,&TCPserver::do_newConnection);
}

TCPserver::~TCPserver()
{
     if (tcpSocket != nullptr)
     {
     if (tcpSocket->state() == QAbstractSocket::ConnectedState)
     tcpSocket->disconnectFromHost(); //断开与客户端的连接
     }
     if (tcpServer->isListening())
     tcpServer->close(); //停止网络监听
     delete ui;
}

QString TCPserver::getLocalIP()
{
     QString hostName= QHostInfo::localHostName(); //本机主机名
     QHostInfo hostInfo= QHostInfo::fromName(hostName);
     QString localIP= "";
     QList<QHostAddress> addrList= hostInfo.addresses(); //本机 IP 地址列表
     if (addrList.isEmpty())
     return localIP;
     foreach(QHostAddress aHost, addrList)
     if (QAbstractSocket::IPv4Protocol == aHost.protocol())
     {
     localIP= aHost.toString();
     break;
     }
     return localIP;
}

void TCPserver::do_newConnection()
{
     tcpSocket= tcpServer->nextPendingConnection(); //创建 socket
     connect(tcpSocket, SIGNAL(connected()), this, SLOT(do_clientConnected()));
     do_clientconnected(); //运行一次槽函数，显示状态
     connect(tcpSocket, SIGNAL(disconnected()),this, SLOT(do_clientDisconnected()));
     connect(tcpSocket,&QTcpSocket::stateChanged,this,&TCPserver::do_socketStateChange);
     do_socketStateChange(tcpSocket->state()); //运行一次槽函数，显示状态
     connect(tcpSocket,SIGNAL(readyRead()), this,SLOT(do_socketReadyRead()));
}

void TCPserver::do_socketStateChange(QAbstractSocket::SocketState socketState)
{
    switch(socketState)
     {
     case QAbstractSocket::UnconnectedState:
     ui->labSocketState->setText("UnconnectedState"); break;
     case QAbstractSocket::HostLookupState:
     ui->labSocketState->setText("HostLookupState"); break;
     case QAbstractSocket::ConnectingState:
     ui->labSocketState->setText("ConnectingState"); break;
     case QAbstractSocket::ConnectedState:
     ui->labSocketState->setText("ConnectedState"); break;
     case QAbstractSocket::BoundState:
     ui->labSocketState->setText("sBoundState"); break;
     case QAbstractSocket::ClosingState:
     ui->labSocketState->setText("ClosingState"); break;
     case QAbstractSocket::ListeningState:
     ui->labSocketState->setText("ListeningState");
     }
}

void TCPserver::do_clientconnected()
{
     ui->textEdit->append("**client socket connected");
     ui->textEdit->append("**peer address:"+
     tcpSocket->peerAddress().toString());
     ui->textEdit->append("**peer port:"+
     QString::number(tcpSocket->peerPort()));
}

void TCPserver::do_clientDisconnected()
{
    ui->textEdit->append("**client socket disconnected");
    tcpSocket->deleteLater();
}

void TCPserver::do_socketReadyRead()
{
    while(tcpSocket->canReadLine())
    ui->textEdit->append("[in] "+tcpSocket->readLine());
}

void TCPserver::on_actStart_clicked()
{
    QString IP= ui->comboIP->currentText(); //IP 地址字符串，如"127.0.0.1"
     quint16 port= ui->spinPort->value(); //端口
     QHostAddress address(IP); //通过 IP 地址字符串创建 QHostAddress 对象
     tcpServer->listen(address,port); //开始监听
     ui->textEdit->append("**开始监听...");
     ui->textEdit->append("**服务器地址："+tcpServer->serverAddress().toString());
     ui->textEdit->append("**服务器端口："
     +QString::number(tcpServer->serverPort()));
     ui->actStart->setEnabled(false);
     ui->actStop->setEnabled(true);
     ui->labListen->setText("正在监听");
}

void TCPserver::on_actStop_clicked()
{
    if (tcpServer->isListening()) //tcpServer 正在监听
     {
     if (tcpSocket != nullptr)
     if (tcpSocket->state() == QAbstractSocket::ConnectedState)
     tcpSocket->disconnectFromHost();
     tcpServer->close(); //停止监听
     ui->actStart->setEnabled(true);
     ui->actStop->setEnabled(false);
     ui->labListen->setText("已停止监听");
     }
}

void TCPserver::on_btnSenf_clicked()
{
    QString msg= ui->editMsg->text();
     ui->textEdit->append("[out] "+msg);
     ui->editMsg->clear();
     ui->editMsg->setFocus();
     QByteArray str= msg.toUtf8();
     str.append("\r\n");
     if(tcpSocket!=nullptr){
         tcpSocket->write(str);
     }
     else return;

}

void TCPserver::on_pushButton_4_clicked()
{
    emit show_Menu();
}
